//
//  PKRequestManager.m
//  PianKe
//
//  Created by lanou on 15/12/22.
//  Copyright © 2015年 yang. All rights reserved.
//

#import "WTRequestManager.h"
#import <Foundation/Foundation.h>
@implementation WTRequestManager

+ (void)requestWithUrlString:(NSString *)urlString parDic:(NSDictionary *)parDic  method:(RequsetType)method success:(Success)success  error:(Error)error
{
    // 网址字符串转化成网址对象
    NSURL *url = [NSURL URLWithString:urlString];
    // 网络请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    // 判断是Post请求还是Get请求
    if (method == POST) {
        [request setHTTPMethod:@"POST"];
        // 判断parDic是否为0,为0无方法体. 不为0需要将字典转化成方法体字符串
        if (parDic.count != 0) {
            NSMutableArray *strArray = [NSMutableArray array];
            for (NSString *key in parDic) {
                NSString *str = [NSString stringWithFormat:@"%@=%@",key,parDic[key]];
                [strArray addObject:str];
            }
           // 字典拼接成字符串,再设置成方法体
           NSString *parString = [strArray componentsJoinedByString:@"&"];
            [request setHTTPBody:[parString dataUsingEncoding:NSUTF8StringEncoding]];
        }
    }
    // 异步请求数据
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
//        // 带缓存的请求
//        NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
//        
//        NSRange a = NSMakeRange(urlString.length - 4, 3);
//        NSString *p = [urlString substringWithRange:a];
//        NSString *savePath = [documentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",p]];
        
//        NSLog(@"%@",urlString);
//         NSLog(@"%@",savePath);
//        NSLog(@"%@",documentPath);
       
       
        // 没有错误就是请求成功,调用成功的block方法
        if (connectionError == nil) {
            // 函数的调用
            success(data);
//            // 存入本地
//             [data writeToFile:savePath atomically:YES];
        }else{
            // 有错误就是请求失败,调用失败时的block方法
              // 函数的调用
            error(connectionError);

//            NSData *pickData = [NSData dataWithContentsOfFile:savePath];
//
//                  success(pickData);
            
        }
        
    }];
}
@end
